package com.application.lucky.activity.me;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;

import com.application.lucky.Lucky;
import com.application.lucky.R;
import com.application.lucky.bean.jsonBean.BankItemBean;
import com.application.lucky.bean.sqliteBean.BankBean;
import com.application.lucky.gen.BankBeanDao;
import com.application.lucky.manager.UserManagers;
import com.application.lucky.request.CallBackEx;
import com.application.lucky.request.UserRequest;
import com.application.lucky.utils.ConnUtil;
import com.application.lucky.widget.TitlebarView;
import com.application.mylibrary.base.BaseActivity;
import com.application.mylibrary.utils.EventBusUtils;
import com.baselib.libnetwork.net.libnetworkcomponent.BaseResponse;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class SelectBankActivity extends BaseActivity {
    private TitlebarView mTitleBar;
    private RecyclerView mRclView;
    private MyAdapter myAdapter;
    private BankBeanDao dao;
    private boolean isBindCard = false;
    private String auth_name;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initView();
    }

    @Override
    public void beforeInit() {

    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_select_bank;
    }

    private void initView() {
        dao = Lucky.getApplication().getDaoSession().getBankBeanDao();
        mTitleBar = findViewById(R.id.title_bar);
        mTitleBar.setOnViewClick(new TitlebarView.onViewClick() {
            @Override
            public void leftClick() {
                finishAnim();
            }

            @Override
            public void rightClick() {

            }
        });
        isBindCard = getIntent().getBooleanExtra("is", false);
        auth_name = getIntent().getStringExtra("auth_name");
        if (isBindCard) {
            mTitleBar.setTitle("银行卡");
        }

        mRclView = findViewById(R.id.rcl_view);
        myAdapter = new MyAdapter(R.layout.item_bank_view);
        mRclView.setLayoutManager(new LinearLayoutManager(this));
        mRclView.setAdapter(myAdapter);
        myAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

            }
        });
        myAdapter.addFooterView(getview());
        myAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                BankBean item = myAdapter.getItem(position);
                if (item != null) {
                    if (isBindCard) {
                        Intent intent = new Intent(SelectBankActivity.this, AddBankActivity.class);
                        intent.putExtra("is", false);
                        intent.putExtra("is_bind", true);
                        intent.putExtra("bean", item);
                        startActivity(intent);
                    } else {
                        EventBusUtils.post(item);
                        finishAnim();
                    }
                }
            }

        });

    }

    private View getview() {
        View view = LayoutInflater.from(this).inflate(R.layout.view_select_bank_foot, null);
        view.findViewById(R.id.rl_add_bank).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent addIntent = new Intent(SelectBankActivity.this, AddBankActivity.class);
                if (ConnUtil.isNotEmpty(myAdapter.getData()) && myAdapter.getData().get(0) != null) {
                    addIntent.putExtra("real_name", myAdapter.getData().get(0).name);
                    addIntent.putExtra("already_bank_num", myAdapter.getData().get(0).num);
                } else {
                    addIntent.putExtra("real_name", auth_name);
                }
                startActivityAnim(addIntent);
            }
        });
        return view;
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadData();
    }

    private void loadData() {
        final List<BankBean> bankBeans = dao.queryBuilder().where(BankBeanDao.Properties.UserId.eq(UserManagers.getInstance().getUserId())).list();
//        List<BankBean> bankBeans = dao.loadAll();
        if (bankBeans != null) {
            myAdapter.setNewData(bankBeans);
        }


        Observable.create(new ObservableOnSubscribe<List<BankBean>>() {

            @Override
            public void subscribe(final ObservableEmitter<List<BankBean>> emitter) throws Exception {
                new UserRequest().getAlreadyBindBank(new CallBackEx<BaseResponse<List<BankItemBean>>>() {
                    @Override
                    public void onFailed(int code) {

                    }

                    @Override
                    public void onSuccess(BaseResponse<List<BankItemBean>> listBaseResponse) {
                        if (ConnUtil.isEmpty(listBaseResponse.dataInfo)) {
                            return;
                        }

                        List<BankItemBean> resBeanList = listBaseResponse.dataInfo;
                        List<BankBean> beanList = new ArrayList<>();
                        for (BankItemBean itemBean : resBeanList) {
                            BankBean bankBean = new BankBean();
                            bankBean.name = itemBean.name; // 卡的人名字
                            bankBean.num = itemBean.bank; // 卡号
                            bankBean.accountAddress = itemBean.bankAddress; // 支行地址
                            bankBean.accountNamw = itemBean.bank; // 银行名字
                            bankBean.requestId = String.valueOf(itemBean.id);//把id换成请求的id，防止id与数据库自增的id字段相互重复导致的问题
                            beanList.add(bankBean);

                            // 更新id到request id上去
                            if (ConnUtil.isNotEmpty(bankBeans)) {
                                List<BankBean> tempList = new ArrayList<>(bankBeans);
                                for (BankBean uiBean : tempList) {
                                    if (TextUtils.isEmpty(uiBean.requestId) && TextUtils.equals(uiBean.num, bankBean.num)) {
                                        uiBean.setRequestId(bankBean.requestId);
                                        BankBeanDao bankBeanDao = Lucky.getApplication().getDaoSession().getBankBeanDao();
                                        bankBeanDao.insertOrReplace(uiBean);
                                    }

                                    // 临时的补漏，后面删除该代码
                                    if (!resBeanList.contains(uiBean)) {
                                        BankBeanDao bankBeanDao = Lucky.getApplication().getDaoSession().getBankBeanDao();
                                        bankBeanDao.delete(uiBean);
                                    }
                                }
                            }
                        }

                        List<BankBean> newBankList = new ArrayList<>();
                        BankBeanDao bankBeanDao = Lucky.getApplication().getDaoSession().getBankBeanDao();
                        for (BankBean item : beanList) {
                            if (ConnUtil.isEmpty(bankBeans) || !bankBeans.contains(item)) {
                                newBankList.add(item);
                                bankBeanDao.insertOrReplace(item);
                            }
                        }

                        emitter.onNext(newBankList);
                    }
                });
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<List<BankBean>>() {

            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(List<BankBean> bankBeans) {
                if (!bankBeans.isEmpty()) {
                    myAdapter.getData().addAll(bankBeans);
                    myAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    static class MyAdapter extends BaseQuickAdapter<BankBean, BaseViewHolder> {
        public MyAdapter(int layoutResId) {
            super(layoutResId);
        }

        @Override
        protected void convert(BaseViewHolder helper, BankBean item) {
            helper.setText(R.id.tv_name, item.accountNamw)
                    .setText(R.id.tv_user_name, item.name)
                    .setText(R.id.tv_num, getPhoneHideInfo(item.num));
        }

        private String getPhoneHideInfo(String number) {
            if (TextUtils.isEmpty(number)) {
                return number;
            }

            int len = number.length();
            return number.substring(0, 4) + " **** **** " + number.substring(len - 4, len);
        }
    }
}
